<?php
/**
 * websocket 消息
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\CacheKey;
use app\model\ConfigModel;
use app\model\FriendModel;
use app\model\MessageModel;
use app\model\SystemMessageModel;
use app\model\TrendsMagModel;
use app\model\TrendsUserLikeModel;
use app\model\UserBlacklistModel;
use app\model\UserCensusCountModel;
use app\model\UserModel;
use app\services\SendMessageServices;
use app\services\UserService;
use GatewayClient\Gateway;
use GatewayWorker\Lib\Db;
use think\Exception;

class Mini extends BaseController
{


    protected $fileType = ['file', 'image', 'video', 'voice'];


    /**
     * 将用户UId绑定到消息推送服务中
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function bindUid()
    {
        $client_id = $this->request->param('client_id');
        $user_id = $this->request->param('user_id');
        try {
            // 如果当前ID在线，将其他地方登陆挤兑下线
            if (Gateway::isUidOnline($user_id)) {
                wsSendMsg($user_id, 'offline', ['id' => $user_id, 'client_id' => $client_id, 'isMobile' => $this->request->isMobile()]);
            }
            Gateway::bindUid($client_id, $user_id);
//            wsSendMsg(0, 'isOnline', ['id' => $user_id, 'is_online' => 1]);
        } catch (\Exception $e) {
            // 未找到用户
            return $this->renderError('error', []);
        }
        return $this->renderSuccess([], 'ok');
    }


    /**
     * 创建联系人
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function addUserContacts()
    {
        $param = $this->request->param();
        $param['create_user'] = $this->uid;
        $param['create_time'] = time();
        $param['update_time'] = time();
        $arr = [$param['friend_user_id'], $this->uid];
        sort($arr);
        $relation = implode(',', $arr) . ',';
        $param['relation'] = $relation;
        $result = FriendModel::where(function ($query) use ($param) {
            $query->where(['create_user' => $this->uid])->where(['friend_user_id' => $param['friend_user_id']]);
        })->whereOr(function ($query) use ($param) {
            $query->where(['friend_user_id' => $this->uid])->where(['create_user' => $param['friend_user_id']]);
        })->find();
//        if ($result) return $this->renderError(lang('您不能重复添加'), [], 10003);
        $data = [];
        if ($result) {
            FriendModel::where('relation', $relation)->update([
                'update_time' => time(),
                'is_del' => 0,
            ]);
        } else {
            $data = FriendModel::create($param);
        }
        return $this->renderSuccess($data, 'ok');
    }

    /**
     * 获取联系人列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */

    public function getContacts()
    {
        $param = $this->request->param();

        if ($param['type'] == 1) {
            $user_id = $this->uid;

            $idArr = FriendModel::where('relation', 'like', "%{$user_id},%")->where('is_del', 0)->column('friend_id');

            $userIdArr1 = FriendModel::whereIn('friend_id', $idArr)->where('is_del', 0)->column('create_user');
            $userIdArr2 = FriendModel::whereIn('friend_id', $idArr)->where('is_del', 0)->column('friend_user_id');

            $arr = array_unique(array_merge($userIdArr1, $userIdArr2));
            $responseArr = array_diff($arr, [$this->uid]);
            $userIds = UserModel::whereIn('id', $responseArr)->where('verification', 'normal')->column('id');
            $friendIdArr1 = FriendModel::whereIn('create_user', $userIds)->where('friend_user_id', $user_id)->where('is_del', 0)->column('friend_id');
            $friendIdArr2 = FriendModel::whereIn('friend_user_id', $userIds)->where('create_user', $user_id)->where('is_del', 0)->column('friend_id');
            $friendId = array_unique(array_merge($friendIdArr1, $friendIdArr2));

            $list = FriendModel::whereIn('friend_id', $friendId)
                ->where('is_del', 0)
                ->field('friend_id,create_user,friend_user_id,create_time,status,update_time')
                ->order(['update_time' => 'DESC'])
                ->paginate()->each(function ($item) {
                    $message_id = $item['friend_user_id'] == $this->uid ? $item['create_user'] : $item['friend_user_id'];
                    $item['number'] = MessageModel::where(['from_user' => $message_id, 'to_user' => $this->uid, 'is_read' => 0])->count();

                    $chat_message = MessageModel::where(['friend_id' => $item['friend_id']])
                        ->order(['create_time' => 'DESC'])
                        ->field(['from_user', 'to_user', 'content', 'type', 'music', 'video', 'image'])->find();
                    $item['chat_message'] = $chat_message;
                    return $item;
                });
        } elseif ($param['type'] == 2) {
            $user_id = $this->uid;
            $idArr = FriendModel::where('relation', 'like', "%{$user_id},%")->where('is_del', 0)->column('friend_id');
            $userIdArr1 = FriendModel::whereIn('friend_id', $idArr)->where('is_del', 0)->column('create_user');
            $userIdArr2 = FriendModel::whereIn('friend_id', $idArr)->where('is_del', 0)->column('friend_user_id');
            $arr = array_unique(array_merge($userIdArr1, $userIdArr2));
            $responseArr = array_diff($arr, [$this->uid]);
            $userIds = UserModel::whereIn('id', $responseArr)->where('verification', 'hidden')->column('id');

            $friendIdArr1 = FriendModel::whereIn('create_user', $userIds)->where('friend_user_id', $user_id)->where('is_del', 0)->column('friend_id');
            $friendIdArr2 = FriendModel::whereIn('friend_user_id', $userIds)->where('create_user', $user_id)->where('is_del', 0)->column('friend_id');
            $friendId = array_unique(array_merge($friendIdArr1, $friendIdArr2));

            $list = FriendModel::whereIn('friend_id', $friendId)->where('is_del', 0)
                ->field('friend_id,create_user,friend_user_id,create_time,status,update_time')
                ->order(['update_time' => 'DESC'])
                ->paginate()->each(function ($item) {
                    $message_id = $item['friend_user_id'] == $this->uid ? $item['create_user'] : $item['friend_user_id'];
                    $item['number'] = MessageModel::where(['from_user' => $message_id, 'to_user' => $this->uid, 'is_read' => 0])->count();

                    $chat_message = MessageModel::where(['friend_id' => $item['friend_id']])
                        ->order(['create_time' => 'DESC'])
                        ->field(['from_user', 'to_user', 'content', 'type', 'music', 'video', 'image'])->find();
                    $item['chat_message'] = $chat_message;
                    return $item;
                });

        } else {
            //这是一个客服
            $basic_service = ConfigModel::where('name', 'basic_service')->cache(true, 60)->value('value');
            $list = FriendModel::where('is_del', 0)->when($param, function ($query) use ($param) {
                return $query->where(function ($query) {
                    $query->where('create_user', $this->uid)->whereOr('friend_user_id', $this->uid);
                });
            })->field('friend_id,create_user,friend_user_id,create_time,status,update_time')
                ->order(['update_time' => 'DESC'])
                ->paginate($param['limit'])->each(function ($item) {
                    $message_id = $item['friend_user_id'] == $this->uid ? $item['create_user'] : $item['friend_user_id'];
                    $item['number'] = MessageModel::where(['from_user' => $message_id, 'to_user' => $this->uid, 'is_read' => 0])->count();
                    $chat_message = MessageModel::where(['friend_id' => $item['friend_id']])
                        ->order(['create_time' => 'DESC'])
                        ->field(['from_user', 'to_user', 'content', 'type', 'music', 'video', 'image'])->find();
                    $item['chat_message'] = $chat_message;
                    return $item;
                });

            $res = $list->toArray();
            $new_array = [];
            $unshift = [];
            if ($this->uid != $basic_service) {
                if ($basic_service > 0) {
                    foreach ($res['data'] as $value) {
                        if ($value['friend_user_id'] != $basic_service) {
                            $new_array[] = $value;
                        }
                        if ($value['friend_user_id'] == $basic_service) {
                            $unshift = $value;
                        }
                    }
                    if (!empty($unshift)) {
                        array_unshift($new_array, $unshift);
                    }
                }
                $res['data'] = $new_array;
            }

            return $this->renderSuccess($res, 'ok');

        }
        return $this->renderSuccess($list, 'ok');
    }


    /**
     * 会员发送消息
     * @return void
     * @author yuncran@126.com
     */
    public function sendMessage()
    {
        $param = $this->request->param();
        $param['is_read'] = 0;
        Gateway::$registerAddress = config('gateway.registerAddress');
        try {
            $user = UserModel::where('id', $this->uid)->field('id,level,nickname,group_id')->find();
            $user2 = UserModel::where('id', $param['to_user'])->field('id,group_id,level,nickname')->find();
            if ($user2['group_id'] != 2) {
                if ($user['level'] == 1) {
                    if (!$this->getSendCount()) {
                        return $this->renderError('请升级为vip后再使用聊天功能');
                    }
                }
            }

            $onlineList = Gateway::getAllUidList();
            $param['from_user'] = $this->uid;
            $param['friend_id'] = SendMessageServices::getFriendId($this->uid, $param['to_user']);
            // 在线 is_online = normal 、 离线
            $param['is_group'] = $user['group_id'] == 1 ? 0 : 2;             // 客服为 2    普通私聊 0
            if ($user['is_private'] != 2) {
                $param['content'] = UserService::getFilter($param['content']);
                SendMessageServices::userSend($param['to_user'], 'chat', $param);
                MessageModel::inData($param);
            }
            //修改时间
            event('Service', ['friend_id' => $param['friend_id'],]);
        } catch (Exception $exception) {
            return $this->renderError(lang('发送失败'));
        }
        return $this->renderSuccess($onlineList, 'ok');
    }

    /**
     * 获取会员今日发送条数
     * @return void
     * @author yuncran@126.com
     */
    public function getSendCount()
    {
        // 获取每天发送条数
        $configValue = ConfigModel::where('id', 22)->value('value');
        $user2 = UserModel::where('id', $this->uid)->field('id,group_id,level,nickname')->find();
        if ($user2['group_id'] != 2) {
            //create_time
            // $user_count = MessageModel::whereTime('create_time', 'today')->where('from_user', $this->uid)->count();
            $user_count = MessageModel::where('from_user', $this->uid)->count();
            if ($configValue == 0) {
                return true;
            }
            if ($configValue) {
                if ($user_count >= $configValue) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取消息统计列表
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function getMessageCount()
    {

        $userCensusCount = UserCensusCountModel::where('user_id', $this->uid)->find();
        if (empty($userCensusCount)) {
            $message = array(
                'all_user_message_number' => 0,  //全部私信消息
                'all_customer_message_number' => 0,
                'all_system_message_number' => 0,

                'user_fans_count' => 0, //粉丝数
                'user_trends_count' => 0, //动态数
                'user_collect_count' => 0, //收藏数
                'user_follow_count' => 0, //关注
                'user_give_count' => 0, //点赞
                'user_refer_count' => 0, //@我的
            );
        } else {
            //客服
            $basic_service = ConfigModel::where('name', 'basic_service')->cache(true, 60)->value('value');
            $user = UserModel::where('id', $basic_service)->field('id,group_id,level,nickname,is_private')->find();
            $basic_service_id = $this->uid;
            if ($basic_service > 0 && !empty($user)) {
                $basic_service_id = $basic_service;
            }            
            $message = array(
                'all_user_message_number' => MessageModel::where(function ($query) {
                    $query->where('to_user', $this->uid)->where('is_read', 0);
                })->where('is_del', 0)->count(),  //全部私信消息

                'all_customer_message_number' => MessageModel::where(function ($query) use($basic_service_id) {
                    $query->where('from_user', $basic_service_id)->where('to_user',$this->uid)->where('is_read', 0);
                })->where('is_del', 0)->count(),

                'all_system_message_number' => SystemMessageModel::where('user_id', $this->uid)->where('is_read', 0)->count(),

                'user_fans_count' => $userCensusCount['user_fans_count'], //粉丝数
                'user_trends_count' => $userCensusCount['user_trends_count'], //动态数
                'user_collect_count' => $userCensusCount['user_collect_count'], //收藏数
                'user_follow_count' => $userCensusCount['user_follow_count'], //关注
                'user_give_count' => TrendsUserLikeModel::where('to_user_id', $this->uid)->where('status', 1)->count(), //点赞
                'user_refer_count' => TrendsMagModel::where('users', $this->uid)->count(), //@我的
            );
        }
        return $this->renderSuccess($message, 'ok');
    }


    /**
     * 删除联系人
     * @return void
     * @author yuncran@126.com
     */
    public function delFriend()
    {
        $param = $this->request->param();
//        $res = FriendModel::where('friend_id', $param['friend_id'])->delete();
        $res = FriendModel::where('friend_id', $param['friend_id'])->update(['is_del' => 1, 'delete_time' => time()]);
        if (!$res) {
            return $this->renderError(lang('删除失败'));
        }
        MessageModel::where('friend_id', $param['friend_id'])->update(['is_read'=>1 , 'update_time'=> time() ]);
        return $this->renderSuccess($res, '删除成功');
    }


    /**
     * 获取查询记录
     * @return void
     * @author yuncran@126.com
     */
    public function getUserChatList()
    {
        $param = $this->request->param();

        $user = UserModel::where('id', $param['to_user'])->field('id,group_id')->find();
        if ($param['to_user'] == 1 || $user['group_id'] == 2) {
            $param['create_user'] = $this->uid;
            $param['create_time'] = time();
            $param['update_time'] = time();
            $param['friend_user_id'] = $param['to_user'];
            $arr = [$param['to_user'], $this->uid];
            sort($arr);
            $param['relation'] = implode(',', $arr) . ',';
            $result = FriendModel::where(function ($query) use ($param) {
                $query->where(['create_user' => $this->uid])->where(['friend_user_id' => $param['to_user']]);
            })->whereOr(function ($query) use ($param) {
                $query->where(['friend_user_id' => $this->uid])->where(['create_user' => $param['to_user']]);
            })->find();
            if (!$result) {
                FriendModel::create($param);
            }
        }
        if (empty($param['to_user'])) return $this->renderError(lang('缺少参数'));
        /** 推送状态 */
        wsSendMsg($param['to_user'], 'is_read', ['user_id' => $this->uid, 'to_user' => $param['to_user'], 'is_read' => 1]);

        //查看黑名单
        $userBlacklist = UserBlacklistModel::where(['user_id' => $param['to_user'], 'to_user_id' => $this->uid])->find();
        if ($userBlacklist) return $this->renderError(lang('您未权限和该会员聊天'));
        // 查询最近的联系人
        $list = MessageModel::field('*')
            
            ->where(function ($query) use ($param) {
                $query->where(['from_user' => $this->uid])->where(['to_user' => $param['to_user']])->where(['is_from' => 0])->where('is_del', 0);
            })
            ->whereOr(function ($query) use ($param) {
                $query->where(['to_user' => $this->uid])->where(['from_user' => $param['to_user']])->where(['is_to' => 0])->where('is_del', 0);
            })
            ->order(['msg_id' => 'DESC'])
            ->paginate($param['limit'])->each(function ($item) {
                return $item;
            });
        $this->status($param);
        return $this->renderSuccess($list, 'ok');
    }


    /**
     * 客服消息清理
     * @return void
     * @author yuncran@126.com
     */
    public function customerStatus()
    {
//        $param = $this->request->param();
//        MessageModel::where(function ($query) use ($param) {
//            $query->where(['to_user' => $this->uid])->where(['from_user' => $param['to_user']]);
//        })->where('is_read', 0)->update(['is_read' => 1, 'update_time' => time()]);
    }

    public function upSemmage()
    {
        $param = $this->request->param();
        if (isset($param['to_user'])) {
            MessageModel::where(function ($query) use ($param) {
                $query->where(['to_user' => $this->uid])->where(['from_user' => $param['to_user']]);
            })->where('is_read', 0)->update(['is_read' => 1, 'update_time' => time()]);
        }
        return $this->renderSuccess([], 'ok');
    }

    /**
     * 更新状态
     * @return void
     * @author yuncran@126.com
     */
    public function status($param)
    {
        MessageModel::where(function ($query) use ($param) {
            $query->where(['to_user' => $this->uid])->where(['from_user' => $param['to_user']]);
        })->where('is_read', 0)->update(['is_read' => 1, 'update_time' => time()]);
        return true;
    }

    /**
     * 清空聊天记录
     * @return void
     * @author yuncran@126.com
     */
    public function userChatDel()
    {
        $param = $this->request->param();
        if ($this->uid == $param['create_user']) {
            /** @var  $from  当会员是发送者时候 */
            MessageModel::where('friend_id', $param['friend_id'])->where('from_user', $param['create_user'])->update(['is_del' => 1, 'is_from' => 1, 'update_time' => time()]);
            MessageModel::where('friend_id', $param['friend_id'])->where('to_user', $param['create_user'])->update(['is_to' => 1, 'update_time' => time()]);
        } else {
            MessageModel::where('friend_id', $param['friend_id'])->where('to_user', $param['to_user'])->update([ 'is_to' => 1, 'update_time' => time()]);
            MessageModel::where('friend_id', $param['friend_id'])->where('from_user', $param['to_user'])->update(['is_from' => 1, 'is_del' => 1,'update_time' => time()]);
        }

        return $this->renderSuccess([], 'ok');
    }

    /**
     * 单向删除聊天记录
     * @return void
     * @author yuncran@126.com
     */
    public function userChatDel_copy()
    {
        $param = $this->request->param();
        $response = MessageModel::where(function ($query) use ($param) {
            $query->where(function ($q) use ($param) {
                $q->where(['from_user' => $param['to_user']])->where('is_from', 1);
            });
//          ->whereOr(function ($q1)  use ($param){
//               $q1->where(['to_user'=>$param['is_to']])->where('is_to',1);
//           }) ;
        })->find();

        if ($response) {
            MessageModel::where(['from_user' => $this->uid])->whereOr(['to_user' => $this->uid])->update(['is_from' => 1, 'update_time' => time()]);
        } else {
            MessageModel::where(['from_user' => $this->uid])->whereOr(['to_user' => $this->uid])->update(['is_to' => 1, 'update_time' => time()]);
        }
        return $this->renderSuccess([], 'ok');
    }

    /**
     * 获取客服
     * @return void
     * @author yuncran@126.com
     */
    public function getService()
    {
        $data = UserModel::where('group_id', 2)->field(['id', 'nickname', 'avatar'])->select();
        return $this->renderSuccess($data, 'ok');
    }

}